﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using JeffWilcox.Utilities.Silverlight;
using Microsoft.Phone.Controls;
using System.Net.Sockets;

namespace WP_Client
{
    public partial class MainPage : PhoneApplicationPage
    {
        private Unit _unit = new Unit();
        private Socket _clientSocket = null;

        // 构造函数
        public MainPage()
        {
            InitializeComponent();
        }

        private void btnLoginOn_Click(object sender, RoutedEventArgs e)
        {
            string userName = this.txtUserName.Text;
            string password = this.txtPassword.Text;
            string name = this.txtName.Text;

            if (string.IsNullOrEmpty(userName)) { MessageBox.Show("请输入用户名"); return; }
            if (string.IsNullOrEmpty(password)) { MessageBox.Show("请输入密码"); return; }
            if (string.IsNullOrEmpty(name)) { MessageBox.Show("请输入名称"); return; }

            string loginOnStr = userName + ";" + JeffWilcox.Utilities.Silverlight.MD5.GetMd5String(password) + ";" + name;

            MessagePackage msgPackage = new MessagePackage { ConnectType = (int)ConnectType.LoginOn, Msg = loginOnStr, Name = name };
            string json = Common.DeserializeObject<MessagePackage>(msgPackage);

            _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SocketAsyncEventArgs socketAsyncEventArgs = new SocketAsyncEventArgs();
            byte[] sendLoginonMsg = Encoding.UTF8.GetBytes(json);
            socketAsyncEventArgs.SetBuffer(sendLoginonMsg, 0, sendLoginonMsg.Length);
            socketAsyncEventArgs.RemoteEndPoint = new DnsEndPoint("10.0.0.175", 9090);
            socketAsyncEventArgs.UserToken = _clientSocket;

            _clientSocket.ConnectAsync(socketAsyncEventArgs);

            socketAsyncEventArgs.SetBuffer(sendLoginonMsg, 0, sendLoginonMsg.Length);
            _clientSocket.SendAsync(socketAsyncEventArgs);
        }
    }
}